<template>
  <a-layout>
    <a-layout-content style="padding: 24px;" >
      <a-modal v-model:visible="isIfNeedWatermarkModalVisible"
               title="是否需要添加水印？"
      >
        <p>
          文件即将开始上传，上传后是否需要添加水印？
        </p>
        <template v-slot:footer>
          <a-button @click="handleUploadFolder(0)">不需要</a-button>
          <a-button type="primary" @click="handleUploadFolder(1)">需要</a-button>
        </template>
      </a-modal>

      <div>
        <a-row class="headRow">
          <a-col :span="12">
            <a-select v-model:value="status" style="width: 200px;" @change = "onSelectChange">
              <a-select-option value="published">已发布</a-select-option>
              <a-select-option value="unpublished">未发布</a-select-option>
            </a-select>
          </a-col>
          <a-col>
            <a-button @click="handleUploadExperimentSet">新建实验集</a-button>
          </a-col>
          <a-col>
            <!--            <input type="file" @change="handleFileChange" webkitdirectory directory multiple />-->
            <!--            <a-button type="primary" @click="handleUploadFolder">上传</a-button>-->

            <a-space direction="horizontal" style="margin-left: 20px">

              <a-button type="primary" @click="triggerFileInput">选择文件或文件夹</a-button>
              <input type="file" ref="fileInput" @change="handleFileChange" webkitdirectory directory multiple hidden="hidden"/>
              <a-button type="primary" @click="showIfNeedWatermarkModal" :disabled="isUploadButtonDisable">上传</a-button>
              <span>{{fileSelectMessage}}</span>

            </a-space>


          </a-col>
        </a-row>
      </div>
      <!-- 表格内容 -->
      <a-table :columns="columns" :data-source="currentTableData" :pagination="false" :scroll="{y:'65vh'}">
        <template #bodyCell="{column, record}">
          <template v-if="column.key === 'action' ">
        <span>
          <a @click="handleCheckDetail(record)">点击进入</a>
          <a-divider type="vertical" />
          <template v-if="status === 'unpublished' ">
            <a :class="{ disabled: isPublishing }" @click="!isPublishing && handlePublish(record)">发布</a>
          </template>
          <a-divider type="vertical" />
          <a @click="handleDownload(record)">下载</a>
        </span>
          </template>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
</template>

<script>
import { defineComponent } from 'vue';
import {Layout, Table, Button, Space, message} from 'ant-design-vue';
import axiosInstance from "@/axios/axios.js";
//TODO 有一个问题，files里不会读取到空文件夹，不知道怎么处理，不过就算不记录空文件夹应该也可以
class Folder{
  constructor(files){
    if (files.length <= 0){
      return
    }
    this.height = 0;
    this.root = new FolderNode()
    const relativePath = files[0].webkitRelativePath;
    this.folderName = relativePath.split('/')[0];

    files.forEach(file => {
      const path = file.webkitRelativePath || file.name
      const parts = path.split('/')
      if (parts.length > this.height){
        this.height = parts.length
      }
      let current = this.root
      parts.forEach((part, index) => {
        if (index === parts.length - 1) {
          //~$开头的文件是wps的临时文件，不处理。
          if (!part.startsWith('~$')) {
            current.addFile(file)
          }

        } else {
          current.addSubFolder(part)
          current = current.subFolders.get(part)
        }
      })
    })
  }

}
class FolderNode {
  constructor() {
    this.subFolders = new Map;
    this.files = [];
  }
  addSubFolder(folderName) {
    if (!this.subFolders.has(folderName)) {
      // 如果键不存在，则创建新的Folder对象并添加到subFolders中
      let newFolder = new FolderNode();
      this.subFolders.set(folderName, newFolder);
    }
  }
  addFile(file) {
    this.files.push(file);

  }
}
export default defineComponent({
  components: {},
  data() {
    return {
      isPublishing: false,
      status: "unpublished",
      publishedData: [],
      unpublishedData: [],
      columns: [
        {
          title: '实验数据集名',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description'
        },
        {
          title: '实验者',
          dataIndex: 'creator',
          key: 'creator'
        },
        {
          title: '领域',
          dataIndex: 'field',
          key: 'field'
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: {customRender: 'action'}
        }
      ],
      files: [],
      folder:{},
      //上传文件夹加载中提示条
      loadingAlert:null,
      fileSelectMessage:"",
      //上传按钮默认不可用，选择文件夹后才可用
      isUploadButtonDisable:true,

      //标识是否需要加水印，默认为0不需要加
      ifNeedWatermark:0,
      isIfNeedWatermarkModalVisible:false,
    };
  },
  mounted() {
    this.getExperimentSetNotPublished()
    this.getExperimentSetPublished()
  },
  computed: {
    currentTableData() {
      return this.status === 'published' ? this.publishedData : this.unpublishedData;
    }
  },
  methods: {
    getExperimentSetPublished() {
      axiosInstance({
        method: "POST",
        url: "/myData/getExperimentSetsPublished",
        headers: {
          Authorization: `Bearer ${this.$cookies.get("jwt")}` // 设置请求头，携带 JWT
        },
        data: {
          username: this.$cookies.get("username"),
          userAddress: this.$cookies.get("userAddress"),
          userSecret: this.$cookies.get("userSecret"),
        },
      })
          .then((response) => {
            console.log("ExperimentSet:", response.data);
            this.publishedData = response.data.data.experimentSets;
          })
          .catch((err) => {
            console.log(err);
          });
    },
    getExperimentSetNotPublished() {
      axiosInstance({
        method: "POST",
        url: "/myData/getExperimentSetsNotPublished",
        headers: {
          Authorization: `Bearer ${this.$cookies.get("jwt")}` // 设置请求头，携带 JWT
        },
        data: {
          username: this.$cookies.get("username"),
          userAddress: this.$cookies.get("userAddress"),
          userSecret: this.$cookies.get("userSecret"),
        },
      })
          .then((response) => {
            console.log("ExperimentSet:", response.data);
            this.unpublishedData = response.data.data.experimentSets;
          })
          .catch((err) => {
            console.log(err);
          });
    },
    handleCheckDetail(record) {
      console.log('点击进入：', record.name);
      this.$router.push({
        path: '/MyData/Batch',
        query: {
          experiment_set_id: record.experiment_set_id,
          experiment_set_name: record.name
        }
      });
    },
    async handlePublish(record) {
      if (this.isPublishing) {
        return; // 如果正在发布，则不执行操作
      }
      this.isPublishing = true;
      try {
        await axiosInstance({
          method: "POST",
          url: "/myData/publish",
          headers: {
            Authorization: `Bearer ${this.$cookies.get("jwt")}` // 设置请求头，携带 JWT
          },
          data: {
            username: this.$cookies.get("username"),
            userAddress: this.$cookies.get("userAddress"),
            userSecret: this.$cookies.get("userSecret"),
            dataId: record.experiment_set_id,
          },
        })
            .then((response) => {
              console.log("PublishExperimentSet:", record);
              this.unpublishedData = this.unpublishedData.filter(item => item.experiment_set_id !== record.experiment_set_id);
              this.publishedData.push(record);
            })
            .catch((err) => {
              console.log(err);
            });
      } finally {
        this.isPublishing = false;
      }
    },
    onSelectChange(value) {
      console.log('Selected', this.status);
      // 实现筛选逻辑
    },
    handleDownload(record) {
      console.log(record)
      axiosInstance({
        method: "POST",
        url: "download/experimentSet",
        headers: {
          Authorization: `Bearer ${this.$cookies.get("jwt")}` // 设置请求头，携带 JWT
        },
        data: {
          username: this.$cookies.get("username"),
          experimentSetName: record.name
        },
      }).then((response) => {
        console.log("下载响应内容：")
        console.log(response.data)
        const link = document.createElement('a');
        link.href = response.data.data;
        link.setAttribute('download', ''); // 可以设置下载文件名，也可以留空
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }).catch((err) => {
        console.log(err);
      });
    },
    handleUploadExperimentSet() {
      this.$router.push({
        path: '/UploadExperimentSet',
      });
    },

    showIfNeedWatermarkModal(){
      this.isIfNeedWatermarkModalVisible=true;
    },

    async handleUploadFolder(needWatermark) {
      this.ifNeedWatermark=needWatermark;
      console.log("是否需要添加水印：",this.ifNeedWatermark)
      if (this.folder.height !== 5){
        message.warn("文件夹格式不符合标准！")
        return
      }
      const formData = new FormData()
      this.files.forEach(file => {
        formData.append('files', file, file.webkitRelativePath)
      })
      formData.append("username", this.$cookies.get("username"))
      formData.append("folderName", this.folder.folderName)
      formData.append("ifWatermark", this.ifNeedWatermark) //新增，表示是否要加水印，1表示加，目前单独上传实验还是会自动加，只有上传folder时会考虑
      this.isIfNeedWatermarkModalVisible=false;
      this.loadingAlert=message.loading("文件上传中，请稍候",0)
      this.files=[]
      this.folder={}
      this.fileSelectMessage=''
      await axiosInstance({
        method: 'POST',
        url: 'upload/folder',
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${this.$cookies.get("jwt")}`
        },
        data: formData,
        timeout:3600000,
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          console.log(`文件上传进度：${percentCompleted}%`);
          this.uploadProgress = percentCompleted;
        }
      })
          .then((response) => {
            console.log(response)
            this.loadingAlert();
            message.success("文件上传成功！")
            //上传按钮恢复为不可用状态
            this.isUploadButtonDisable=true;
          })
          .catch((err) => {
            console.log(err);
            this.loadingAlert();
            message.error("文件上传失败，请检查网络设置")
            //上传按钮恢复为不可用状态
            this.isUploadButtonDisable=true;
          });
    },

    //点击文件上传按钮激活文件input标签
    //文件上传按钮单纯为了好看
    triggerFileInput(){
      this.$refs.fileInput.click();
    },

    handleFileChange(event) {

      const files = event.target.files;

      //判断上传的文件是否合法
      //目前只判断名称是否重复
      var requestFileName="";
      if (files.length === 0) {
        this.fileSelectMessage = '';
      } else if (files.length === 1 && files[0].webkitRelativePath === '') {
        requestFileName=files[0].name;
      } else {
        requestFileName=files[0].webkitRelativePath.split('/')[0];
      }
      const requestPath=this.$cookies.get("username")+"/"+requestFileName;
      const encodeRelativePath=encodeURIComponent(requestPath);
      axiosInstance({
        method: "GET",
        url: "common/getIfFileExist?relativePath="+encodeRelativePath,
        headers: {
          Authorization: `Bearer ${this.$cookies.get("jwt")}` // 设置请求头，携带 JWT
        }
      }).then((response) => {
        console.log("合法性请求响应为：",response)
        if (response.data.data==='exist'){
          message.error("实验集名称已存在！")
        }else {
          if (files.length === 0) {
            this.fileSelectMessage = '';
          } else if (files.length === 1 && files[0].webkitRelativePath === '') {
            this.fileSelectMessage = `选中文件: ${files[0].name}`;
          } else {
            const folderName = files[0].webkitRelativePath.split('/')[0];
            this.fileSelectMessage = `选中文件夹: ${folderName}`;
          }

          this.files = Array.from(event.target.files)
          this.buildFileStructure(this.files)
          console.log("创建文件夹树")
          //上传按钮可用
          this.isUploadButtonDisable=false;
        }
      }).catch((err) => {
        console.log(err);
      });

    },
    buildFileStructure(files) {
      this.folder = new Folder(files)
      console.log(this.folder.height)
    },

  }
});

</script>

<style scoped>
/* 在这里添加一些样式来美化你的界面 */
.headRow {
  margin: 20px;
}
.disabled {
  pointer-events: none;
  opacity: 0.5;
}
</style>
